const momentService = require("../service/moment.service");
const labelMomentService = require("../service/label.moment.service");

class momentController {
  // 发布动态
  async create(ctx, next) {
    // 获取发表动态内容
    const { content } = ctx.request.body;
    // 判断内容长度
    if (!content) {
      ctx.body = {
        code: 500,
        message: "动态的内容不能为空",
      };
      return;
    }

    // 获取发布动态的用户id
    const { id } = ctx.user;

    const result = await momentService.create(content, id);

    ctx.body = {
      code: 0,
      message: "创建动态成功~",
      data: result,
    };
  }

  // 获取列表
  async list(ctx, next) {
    const { offset, size } = ctx.query;
    // 从数据库拿去信息
    const result = await momentService.queryList(offset, size);

    // 返回数据
    ctx.body = {
      code: 0,
      total: result.length,
      data: result,
    };
  }

  // 查询某一个动态的详情
  async detail(ctx, next) {
    const { momentId } = ctx.params;

    const result = await momentService.queryById(momentId);

    // 返回数据
    ctx.body = {
      code: 0,
      data: result,
    };
  }

  // 更新某条动态
  async update(ctx, next) {
    try {
      const { momentId } = ctx.params;
      const { content } = ctx.request.body;

      const result = await momentService.updataMonent(content, momentId);
      ctx.body = {
        code: 0,
        data: result,
      };
    } catch (error) {
      console.log(error);
    }
  }

  // 删除动态
  async deleteMoment(ctx, next) {
    try {
      const { momentId } = ctx.params;

      const result = await momentService.deleteMoment(momentId);
      ctx.body = {
        code: 0,
        data: result,
        message: "删除动态成功~",
      };
    } catch (error) {
      console.log("deleteMoment", error);
    }
  }

  // 添加label关系
  async addLabels(ctx, next) {
    const labels = ctx.labels;
    const { momentId } = ctx.params;

    try {
      for (let label of labels) {
        // 判断label_id与moment_id是否已经存在该数据
        const isExists = await labelMomentService.hasLabel(momentId, label.id);
        if (!isExists) {
          // 如果不存在，执行插入操作
          const insertResult = await labelMomentService.create(
            momentId,
            label.id
          );
        }
      }

      ctx.body = {
        code: 0,
        message: "建立关系成功~",
      };
    } catch (error) {
      ctx.body = {
        code: -3001,
        message: "为动态添加标签失败~",
      };
    }
  }
}
module.exports = new momentController();
